package com.sias.judgeservice.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.sias.model.model.codsandbox.JudgeInfo;
import com.sias.model.model.dto.question.JudgeCase;
import com.sias.model.model.dto.question.JudgeConfig;
import com.sias.model.model.entity.Question;
import com.sias.model.model.enums.JudgeInfoMessageEnum;

import java.util.List;

/**
 * @author 吴文杰
 * @version 1.0
 * @since 2023/12/10 20:48
 */
public class DefaultJudgeStrategy implements JudgeStrategy {

  @Override
  public JudgeInfo doJudge(JudgeContext judgeContext) {
    JudgeInfo judgeInfoResponse = new JudgeInfo();

    JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
    List<String> inputList = judgeContext.getInputList();
    List<String> outputList = judgeContext.getOutputList();
    List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
    Question question = judgeContext.getQuestion();


    Long memory = judgeInfo.getMemory();
    Long time = judgeInfo.getTime();


    judgeInfoResponse.setMemory(memory);
    judgeInfoResponse.setTime(time);

    // 判题结果初始状态
    JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.ACCEPTED;

    // 输出结果数量是否相等
    if (outputList.size() != inputList.size()) {
      judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
      judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
      return judgeInfoResponse;
    }
    // 遍历结果比较是否相等
    for (int i = 0; i < outputList.size(); i++) {
      JudgeCase judgeCase = judgeCaseList.get(i);
      if (!judgeCase.getOutput().equals(outputList.get(i))) {
        judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
        judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
        return judgeInfoResponse;
      }
    }
    String judgeConfigStr = question.getJudgeConfig();
    JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
    Long timeLimit = judgeConfig.getTimeLimit();
    Long memoryLimit = judgeConfig.getMemoryLimit();
    if (memory > memoryLimit) {
      judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
      judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
      return judgeInfoResponse;
    }
    if (time > timeLimit) {
      judgeInfoMessageEnum = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
      judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
      return judgeInfoResponse;
    }
    judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
    return judgeInfoResponse;
  }
}
